from machine import I2C,Pin,ADC
from time import sleep
from ssd1306 import SSD1306_I2C #从 ssd1306 模块中导入 SSD1306_I2C 子模块
i2c = I2C(sda=Pin(45), scl=Pin(46))
#OLED 显示屏初始化：128*64 分辨率, I2C 地址是 0x3c
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)

oled.text("Hello ESP32", 0, 0) #写入第 1 行内容
oled.text("ESP32 TEST", 0, 20) #写入第 2 行内容
oled.text("OLED OK1", 0, 50) #写入第 3 行内容
oled.show() #OLED 执行显示

adcx=ADC(Pin(1,Pin.OUT))
adcx.atten(ADC.ATTN_11DB)


adcy=ADC(Pin(2,Pin.OUT))
adcy.atten(ADC.ATTN_11DB)

sw = ADC(Pin(3,Pin.IN,Pin.PULL_UP))

def ValConver(adcValue):
    CV=(3.3*adcValue/4095)/(3.3)*100
    CV=round(CV)
    return CV


if __name__=="__main__":
    while True:
        adcXv = ValConver(adcx.read())
        adcYv = ValConver(adcy.read())
        sleep(0.5)
        print(f"x={adcXv},y={adcYv},sw={sw}")
        if adcXv<40:
            oled.fill(0)
            oled.text("<--left"+str(adcXv), 0, 0)
            oled.show() #OLED 执行显示
            print("摇杆向左");
        elif adcXv>60:
            oled.fill(0)
            oled.text("right-->", 0, 10)
            oled.show() #OLED 执行显示
            print("摇杆向右")
        elif adcYv<40:
            oled.fill(0)
            oled.text("摇杆向上^", 0, 20)
            oled.show() #OLED 执行显示
            print("摇杆向上");
        elif adcYv>60:
            oled.fill(0)
            oled.text("摇杆向下|", 0, 30)
            oled.show() #OLED 执行显示
            print("摇杆向下")
        else:
            oled.fill(0)
            oled.text("摇杆按键触发|", 0, 40)
            oled.show() #OLED 执行显示
            print("摇杆按键触发")
        